import { getUserCenter } from '@/api/user'
import cache from '@/utils/cache'
import { defineStore } from 'pinia'

interface UserSate {
    userInfo: Record<string, any>
    token: string | null
    temToken: string | null
    roles: string[],
    permissions: string[]
}
export const useUserStore = defineStore({
    id: 'userStore',
    state: (): UserSate => ({
        userInfo: {},
        roles: [],
        permissions: [],
        token: cache.getToken() || null,
        temToken: null
    }),
    getters: {
        isLogin: (state) => !!state.token
    },
    actions: {
        async getUser() {
            const res = await getUserCenter()
            if (res.code === 200) {
                this.userInfo = res.user
                this.roles = res.roles
                this.permissions = res.permissions
            } else this.logout()
        },
        login(token: string) {
            this.token = token
            cache.setToken(token)
        },
        logout() {
            this.token = ''
            this.userInfo = {}
            cache.clearToken()
        }
    }
})
